package plugs

import (
	"context"
	"fmt"

	"gitee.com/wu-jin-feng/kinfu/fgin"
	"google.golang.org/grpc"
)

func init() {
	// grpc服务端中间件
	fgin.RegisteGrpcMiddPlug("my_midd", &MyMidd{})
	// grpc客户端中间件
	fgin.RegisteGrpcClientMiddPlug("my_midd", &MyClientMidd{})
}

type myStr string

var myKey1 myStr = "MyClientMidd"
var myKey myStr = "MyMidd"

// 服务端中间件
type MyMidd struct {
	ServiceName string `yaml:"service_name" json:"service_name"`
}

func (c *MyMidd) Start(ctx context.Context, req any, info *grpc.UnaryServerInfo, logger *fgin.FginSugaredLogger) (context.Context, error) {
	fmt.Println("my middware start11", c, req, info)
	fmt.Println("")
	fmt.Println("my middware ctx:", ctx.Value(myKey))
	fmt.Println("")

	ctx = context.WithValue(ctx, myKey, "grpc middware start")
	return ctx, nil
	// return fmt.Errorf("my middware start error")
}

func (c *MyMidd) AfterStart(ctx context.Context, req any, info *grpc.UnaryServerInfo, plugsErr error, logger *fgin.FginSugaredLogger) error {
	fmt.Println("my middware after start :", c, req, info)
	fmt.Println("")
	fmt.Println("my middware after start ctx:", ctx.Value(myKey))
	fmt.Println("")
	return nil
	// return fmt.Errorf("my middware after start error")
}

// 客户端中间件
type MyClientMidd struct {
	ServiceName string `yaml:"service_name" json:"service_name"`
}

func (c *MyClientMidd) Start(ctx context.Context, method string, req, reply any, logger *fgin.FginSugaredLogger) (context.Context, error) {
	fmt.Println("my client middware start11", c, method, req, reply)
	fmt.Println("")
	fmt.Println("my client middware ctx:", ctx.Value(myKey1))
	fmt.Println("")
	ctx = context.WithValue(ctx, myKey1, "grpc client middware start")
	return ctx, nil
	// return fmt.Errorf("my client middware start error")
}

func (c *MyClientMidd) AfterStart(ctx context.Context, method string, req, reply any, plugsErr error, logger *fgin.FginSugaredLogger) error {
	fmt.Println("my client middware after start :", c, method, req, reply)
	fmt.Println("")
	fmt.Println("my client middware after start  ctx:", ctx.Value(myKey1))
	fmt.Println("")
	return nil
	// return fmt.Errorf("my client middware after start error")
}
